package com.jiang.jixiang.ui;

import android.os.Bundle;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jiang.jixiang.R;
import com.jiang.jixiang.api.ApiUrl;
import com.jiang.jixiang.bean.DeviceLeaseBean;
import com.jiang.jixiang.bean.DeviceScanBean;
import com.jiang.jixiang.bean.PayTypeBean;
import com.jiang.jixiang.databinding.ActivityScanresultBinding;
import com.jiang.jixiang.network.CommonalityModel;
import com.jiang.jixiang.network.NetWorkListener;
import com.jiang.jixiang.network.okHttpModel;
import com.jiang.jixiang.tools.PriceUtils;
import com.jiang.jixiang.ui.adapter.PayTypeAdapter;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.WebViewClient;
import com.ws.universal.tools.Constants;
import com.ws.universal.tools.base.BaseActivity;
import com.ws.universal.tools.base.ManageActivity;
import com.ws.universal.tools.bottomdialog.PopBottonDialog;
import com.ws.universal.tools.countdown.CommitTimer;
import com.ws.universal.tools.eventbus.BaseBusData;
import com.ws.universal.tools.eventbus.BusCode;
import com.ws.universal.tools.eventbus.EventBusUtil;
import com.ws.universal.tools.utils.CacheUtils;
import com.ws.universal.tools.utils.GsonUtils;
import com.ws.universal.tools.utils.LogcatUtils;
import com.ws.universal.tools.utils.StringUtils;
import com.ws.universal.tools.utils.ThreadUtils;
import com.ws.universal.tools.utils.ToastUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.TimeUnit;


public class ScanResultActivity extends BaseActivity implements NetWorkListener {
    private ActivityScanresultBinding binding;
    private Bundle bundle;
    private String device_code;
    private DeviceScanBean deviceScanBean;
    private DeviceLeaseBean deviceLeaseBean;
    private boolean isBuy;
    private String pay_type;
    private String pay_id;
    private PopBottonDialog autoDialog;// 生日选择
    //轮询
    private Timer timer;

    private PayTypeAdapter payTypeAdapter;
    private PayTypeBean payTypeBean;

    @Override
    protected void initCreate(Bundle savedInstanceState) {
        ManageActivity.putActivity(this.getClass().getSimpleName(), this);
        binding = ActivityScanresultBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EventBusUtil.resgisterEventBus(this);
        bundle = getIntent().getExtras();
        device_code = bundle.getString("device_code");
        LogcatUtils.e(" device_code " + device_code);
    }

    @Override
    protected void initView() {
        binding.inTitle.titleTextTv.setText(R.string.rental_information);

        binding.inTitle.titleLeftBtn.setOnClickListener(view -> {
            onBackPressed();
        });
        binding.btnRental.setChangeAlphaWhenPress(true);

        binding.btnRental.setOnClickListener(view -> {
            isBuy = false;
            deviceLease();
            //pageJump(PayMethodActivity.class);


        });
        payTypeAdapter = new PayTypeAdapter();
        LinearLayoutManager manager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }

            @Override
            public boolean canScrollHorizontally() {
                return false;
            }
        };
        binding.rcyData.setLayoutManager(manager);
        binding.rcyData.setAdapter(payTypeAdapter);
        payTypeAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                indexPosition = position;
                toggleSelection();

            }
        });
        loadData();
        loadPayData();
    }

    private int indexPosition;

    private void toggleSelection() {
        //单选
        for (int i = 0; i < payTypeAdapter.getData().size(); i++) {
            if (i == indexPosition) {
                payTypeAdapter.getData().get(indexPosition).setChoose(true);
            } else {
                payTypeAdapter.getData().get(i).setChoose(false);
            }
        }

        payTypeAdapter.notifyDataSetChanged();
    }
    //预授权
    private void preAuthorization(String payment_token) {

        Map<String, String> params = new HashMap<>();
        params.put("device_code", device_code);
        params.put("payment_token", payment_token);
        //okHttpModel.postSuccess(ApiUrl.stripeFreeze_Api, params, ApiUrl.stripeFreeze_Api_ID, this);
    }

    //验证预授权
    private void verification(String pay_id) {
        Map<String, String> params = new HashMap<>();
        params.put("pay_id", pay_id);
        /*okHttpModel.postSuccess(ApiUrl.validationFreeze_Api, params, ApiUrl.validationFreeze_Api_ID, this);*/
    }

    private void loadData() {
        showProgressDialog(false);
        Map<String, String> params = new HashMap<>();
        params.put("qrcode", device_code);
        okHttpModel.post(ApiUrl.deviceScan_Api, params, ApiUrl.deviceScan_Api_ID, this);
    }
    private void loadPayData() {
        Map<String, String> params = new HashMap<>();
        okHttpModel.post(ApiUrl.recharge_Api, params, ApiUrl.recharge_Api_ID, this);
    }

    public void onSucceed(JSONObject jsonData, int id, CommonalityModel commonality) {
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {

            case ApiUrl.deviceScan_Api_ID:
                stopProgressDialog();
                deviceScanBean = GsonUtils.parseJObject(data.toString(), DeviceScanBean.class);
                if (deviceScanBean != null) {
                    //GlideUtils.CreateImageRound(deviceScanBean.getSeller_picture(), binding.imgSeller);
                    binding.tvSellerName.setText(deviceScanBean.getStore_name());
                    binding.tvAddress.setText(deviceScanBean.getStore_name());
                    binding.tvMoney.setText(StringUtils.getString(deviceScanBean.getUnit(), "/ ", getString(R.string.money), PriceUtils.getPrice(deviceScanBean.getAmount())));

                }

                break;
            case ApiUrl.recharge_Api_ID:
                stopProgressDialog();
                payTypeBean = GsonUtils.parseJObject(jsonData.toString(), PayTypeBean.class);
                if (payTypeBean != null) {
                    payTypeAdapter.setList(payTypeBean.getData());
                    payTypeAdapter.setChoosed(0);


                }
                break;
            case ApiUrl.deviceLease_Api_ID:
                deviceLeaseBean = GsonUtils.parseJObject(jsonData.toString(), DeviceLeaseBean.class);
                timerFinish();
                CacheUtils.setString(Constants.order_no, data.optString("order_no"));
                CacheUtils.setBoolean(Constants.isIease, true);
                BaseBusData baseBusData = new BaseBusData(BusCode.showMainTip);
                EventBusUtil.postEvent(baseBusData);
                Bundle bundle = new Bundle();
                bundle.putString("hintOne", getString(R.string.payment_successful));
                bundle.putString("hintTwo", getString(R.string.pick_up_your_power_bank));
                stopProgressDialog();
                pageJump(SuccessActivity.class, bundle);
                finish();
                ToastUtils.showShort(commonality.getMessage());
                break;
           /* case ApiUrl.validationPay_Api_ID:
                ManageActivity.removeActivity("PayTypeActivity");
                ThreadUtils.cancel(task);
                showProgressDialog(false);
                deviceLease();
                break;*/


        }
    }

    @Override
    public void onFail(JSONObject jsonData, int id, CommonalityModel commonality) {
        stopProgressDialog();
        ToastUtils.showShort(commonality.getMessage());
        JSONObject data = jsonData.optJSONObject("data");
        switch (id) {
            case ApiUrl.deviceScan_Api_ID:
                if (commonality.getStatusCode() == 301) {
                    onBackPressed();
                }
                break;
            case ApiUrl.deviceLease_Api_ID:
                if (commonality.getStatusCode() == 2) {
                    onBackPressed();
                } else if (commonality.getStatusCode() == 3) {
                    bundle = new Bundle();
                    bundle.putString("amount", data.optString("amount"));
                    pageJump(PayTypeActivity.class, bundle);
                }
                break;
           /* case ApiUrl.validationPay_Api_ID:
                if (validationPayCount > 0) {
                    validationPayCount--;
                }
                if (validationPayCount == 0) {
                    stopProgressDialog();
                    ThreadUtils.cancel(task);
                    ToastUtils.showShort(commonality.getMessage());
                }

                break;*/
        }
    }

    @Override
    public void onError(int id, Exception e) {
        stopProgressDialog();
        ToastUtils.showShort(e.getMessage());
    }

    //租借
    private void deviceLease() {
        showProgressDialog(false);
        Map<String, String> params = new HashMap<>();
        params.put("device_code", device_code);
        params.put("is_credit", "false");
        okHttpModel.post(ApiUrl.deviceLease_Api, params, ApiUrl.deviceLease_Api_ID, this);
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void showAutoDialog(String loadH5Url) {
        autoDialog = PopBottonDialog.create(getSupportFragmentManager());
        autoDialog.setLayoutRes(R.layout.dialog_auto);
        autoDialog.setViewListener(new PopBottonDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                initAutoDialog(v, loadH5Url);
            }


        });
        autoDialog.setDimAmount(0.3f);
        autoDialog.setTag("showSelectImgDialog");

        autoDialog.show();
    }

    private void initAutoDialog(View view, String loadH5Url) {
        FrameLayout webAuto = view.findViewById(R.id.webAuto);
        AgentWeb mAgentWeb = AgentWeb.with(this).setAgentWebParent(webAuto, new FrameLayout.LayoutParams(-1, -1)).useDefaultIndicator().setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                LogcatUtils.e(" initAutoDialog " + request.getUrl().toString());
                LogcatUtils.e(" initAutoDialog " + request.getMethod().toString());
                LogcatUtils.e(" initAutoDialog " + request.getUrl().toString().indexOf("yookassaCallBack"));

                if (request.getUrl().toString().indexOf("yookassaCallBack") > 0) {
                    autoDialog.dismiss();
                    showProgressDialog(false);
                    polling();
                }

                return super.shouldOverrideUrlLoading(view, request);
            }
        }).createAgentWeb().ready().go(loadH5Url);

        AgentWebConfig.clearDiskCache(this.getContext());
    }

    private void polling() {
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new CommitTimer() {
            @Override
            public void run() {
                verification(pay_id);
            }
        }, 0, 1 * 1000);////Teask，延时时间，轮询间隔
    }


    @Subscribe(threadMode = ThreadMode.MAIN)  //3.0之后，需要加注解
    public void onEventMainThread(BaseBusData data) {
        switch (data.action) {
           /* case BusCode.addCardBuLease:
                deviceLease();

                break;*/

            case BusCode.top_Up_Deposit://验证充值
                validationPayCount = 40;
                showProgressDialog(false);
                order_id = data.str;
                ThreadUtils.executeBySingleAtFixRate(task, 3, TimeUnit.SECONDS);
                break;


        }

    }

    private ThreadUtils.Task task = new ThreadUtils.Task() {
        @Override
        public Object doInBackground() throws Throwable {
            return null;
        }

        @Override
        public void onSuccess(Object result) {

            validationPay();
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onFail(Throwable t) {

        }
    };

    private String order_id;
    private int validationPayCount = 40;

    private void validationPay() {
        LogcatUtils.e(" validationPay执行");
        Map<String, Object> params = new HashMap<>();
        params.put("order_id", order_id);
       // okHttpModel.postJson(ApiUrl.validationPay_Api, params, ApiUrl.validationPay_Api_ID, this);

    }

    @Override
    protected void FinishDesTroy() {
        timerFinish();
        //ThreadUtils.cancel(task);
        ManageActivity.removeActivity(this.getClass().getSimpleName());
        EventBusUtil.unResgisterEventBus(this);
    }


    private void timerFinish() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
        }

    }

}
